package trading.data;

import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import trading.Parameters;
import trading.formulas.functions.IDataFunctionProvider;
import trading.formulas.functions.IFunction;

public class Controller implements IDataType {
	
	//TODO: ONLY SUPPORT DAY TICK NOW
	static public IStockTickDataCollection getTickData()
	{
		IStockTickDataCollection dataMap = DayTickData.DEFAULT_DAYTICKDATA;
		
		return dataMap;
	}
	
	static public float getValueOn(IStockTickDataCollection dataCollection, int index, String type)
	{
		Calendar point = dataCollection.getTickDataList().get(index);
		
		IStockTickData data = (IStockTickData)dataCollection.getTickDataMap().get(point);
		return getTickValue(data, type);
	}
	
	static public void setValueOn(IStockTickDataCollection dataCollection, int index, String type, float value)
	{
		Calendar point = dataCollection.getTickDataList().get(index);
		
		IStockTickData data = (IStockTickData)dataCollection.getTickDataMap().get(point);
		data.setData(type, value);
	}
	
	static public int getIndex(IStockTickDataCollection dataCollection, Calendar cal, boolean forward)
	{
		cal = findProperCalendar(dataCollection, cal, forward);
		return dataCollection.getTickDataList().indexOf(cal);
	}
	
	public static Calendar findProperCalendar(IStockTickDataCollection dataCollection, Calendar c, boolean forward)
	{
		List<Calendar> list = dataCollection.getTickDataList();
		if(list.contains(c))
		{
			return c;
		}
		
		Calendar preCal = null;
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			
			Calendar calendar = (Calendar) iterator.next();
			if(calendar.after(c)){
				if(forward)
				{
					return calendar;
				}
				else
				{
					if(preCal != null)
					{
						return preCal;
					}
					else
					{
						return calendar;
					}
				}
			}
			
			preCal = calendar;
		}
		
		throw new RuntimeException("It's unavailable time!"  + " Calendar : " + c + " Forward : " + forward);
	}
	
	public static Calendar createZeroCaledar()
	{
		Calendar cal = Calendar.getInstance();
		cal.set(0, 0, 0, 0, 0, 0);
		cal.set(Calendar.MILLISECOND, 0);
		return cal;
	}
	
	static private float getTickValue(IStockTickData data, String type)
	{
		return data.getData(type);
	}
	
	/**
	 * used as data type name for IStockTickDataExt
	 * @return
	 */
	static public String getDatatypeName(IFunction func, String typeName, IDataFunctionProvider provider)
	{
		StringBuffer sb = new StringBuffer();
		String name = func.getName();
		sb.append(name).append("_");
		Parameters params = func.getParameters();
		sb.append(params.getParamsAsKey());
		if(typeName != null && !typeName.equals(""))
		{
			sb.append("_").append(typeName);
		}
		
		sb.append("_").append(provider.getName());
			
		return sb.toString();
	}
	
}
